package com.itcc.controller;

import com.itcc.domain.Book;
import com.itcc.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @PostMapping    //添加
    public Result insert(@RequestBody Book book) {
        System.out.println("insert book ==> " + book);
        boolean flag = bookService.insert(book);
        return new Result(flag ? Code.INSERT_OK : Code.INSERT_ERR, flag);
    }

    @RequestMapping(value = "/SelectById/{keyword}", method = RequestMethod.GET)
    public Result Select(@PathVariable String keyword){
        List<Book> bookList = bookService.selectOther(keyword);
        Integer code = bookList != null ? Code.Select_Other_OK : Code.SELECT_ALL_ERR;
        String msg = bookList != null ? "" : "数据查询失败，请重试！";
        return new Result(code, bookList, msg);
    }

    @DeleteMapping("/{id}") //删除
    public Result delete(@PathVariable Integer id) {
        if(id == 1 || id ==2)
            System.out.println("此条数据不给予删除！！！ id: " + id );
        else
            System.out.println("delete book ==> id: " + id);
        boolean flag = bookService.delete(id);
        return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR, flag);
    }

    @PutMapping //更改
    public Result update(@RequestBody Book book) {
        System.out.println("update book ==> id: " + book.getId());
        boolean flag = bookService.update(book);
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, flag);
    }

    @GetMapping("/{id}")    //查询
    public Result findById(@PathVariable Integer id) {
        if(id == 1 || id ==2)
            System.out.println("此条数据不给予删除！！！ id: " + id );
        else
            System.out.println("find book ==> id: " + id);
        Book book = bookService.findById(id);
        Integer code = book != null ? Code.SELECT_SINGLE_OK : Code.SELECT_SINGLE_ERR;
        String msg = book != null ? "" : "数据查询失败，请重试！";
        return new Result(code, book, msg);
    }

    @GetMapping
    public Result selectAll() {
        System.out.println("selectAll book...");
        List<Book> bookList = bookService.selectAll();
        Integer code = bookList != null ? Code.SELECT_ALL_OK : Code.SELECT_ALL_ERR;
        String msg = bookList != null ? "" : "数据查询失败，请重试！";
        return new Result(code, bookList, msg);
    }

}
